<?php

trait Trait_Api_Distributor
{
    use Trait_Api_Model;

    //获取下级分销商/客户数
    public function get_member_num($mid, $is_member = 0)
    {
        $level_num = Model_Fenxiao_Config::get_val('cfg_fenxiao_level_num');
        $fenxiao_level_num = $level_num == 2 ? 2 : 3;
        $sub_mids = Model_Fenxiao::get_sub_mids($mid, $fenxiao_level_num);
        if (empty($sub_mids)) {
            return 0;
        }
        if ($is_member == 0) {
            $num = DB::select(DB::expr("count(*) as num"))->from('fenxiao')
                ->where('memberid', 'in', $sub_mids)
                ->and_where('status', '=', 1)
                ->execute()
                ->get('num');
        } else {
            $sub_mids = Model_Fenxiao::get_sub_mids($mid, 1);
            $num = DB::select(DB::expr("count(*) as num"))->from('fenxiao')
                ->where('memberid', 'in', $sub_mids)
                ->and_where('status', '=', -1)
                ->execute()
                ->get('num');
        }
        return $num;
    }

    //获取返佣总和
    public function get_total_profit($mid)
    {
        $total = DB::select(DB::expr("sum(amount) as total"))->from('fenxiao_record')
            ->where('memberid', '=', $mid)
            ->and_where('type', '=', 0)
            ->execute()
            ->get('total');
        return $total;
    }

    //获取已付款，但未返佣的佣金总和
    public function get_total_unfinish_profit($mid)
    {
        $order = DB::select('a.*')->from(array('fenxiao_data', 'a'))->join(array('member_order', 'b'))
            ->on('a.order_id', '=', 'b.id')
            ->where_open()
            ->where('a.memberid', '=', $mid)
            ->or_where('a.memberid1', '=', $mid)
            ->or_where('a.memberid2', '=', $mid)
            ->or_where('a.memberid3', '=', $mid)
            ->where_close()
            ->and_where('b.status', '=', 2)
            ->execute()->as_array();
        if (count($order) < 1) {
            return 0;
        }
        $info = array(
            0 => array(),//自购订单
            1 => array(),//下1级分销订单
            2 => array(),//下2级分销订单
            3 => array(),//下3级分销订单
        );

        foreach ($order as $v) {
            if ($v['memberid'] == $mid) {
                array_push($info[0], $v['order_id']);
            }
            if ($v['memberid1'] == $mid) {
                array_push($info[1], $v['order_id']);
            }
            if ($v['memberid2'] == $mid) {
                array_push($info[2], $v['order_id']);
            }
            if ($v['memberid3'] == $mid) {
                array_push($info[3], $v['order_id']);
            }
        }
        $total = 0;
        foreach ($info as $k => $v) {
            if (count($v) > 0) {
                $order_id = implode(',', $v);
                $sum_sql = $k < 1 ? "sum(fx_self) as price" : "sum(fx_top{$k}) as price";
                $price = DB::select(DB::expr($sum_sql))->from('member_order_compute')->where(
                    "order_id IN({$order_id})"
                )->execute()->get('price');
                $total = bcadd($total, $price, 2);
            }
        }
        return $total;
    }

    // 检查会员是否是分销商
    public function check_member_distribution($userid)
    {
        $result = false;
        if (St_Functions::is_normal_app_install('mobiledistribution')) {
            $result = DB::select('id', 'status', 'isfrozen', 'fxcode')->from('fenxiao')->where(
                'memberid',
                '=',
                $userid
            )->execute()->current();
        }

        if ( ! empty($result)) {
            $result['isfenxiao'] = $result['status'] == 1 && $result['isfrozen'] == 0 ? true : false;
            switch ($result['status']) {
                case -1:
                    $result = false;
                    break;
                case 0:
                    $result['statusname'] = '等待审核';
                    break;
                case 1:
                    $result['statusname'] = '审核通过';
                    break;
                case 2:
                    $result['statusname'] = '审核不通过';
                    break;
            }
        } else {
            $result = false;
        }

        return $result;
    }

    /**
     * 获取分销客户
     * @param $params
     * @return mixed
     */
    public function get_submembers($params)
    {
        $mid = $params['mid'];
        $fxcode = $params['fxcode'];
        $keyword = $params['keyword'];
        $page = $params['page'] < 1 ? 1 : $params['page'];
        $pagesize = $params['pagesize'] ? $params['pagesize'] : 10;
        $offset = ($page - 1) * $pagesize;
        $builder = DB::select('a.memberid', 'a.fxjointime', 'a.fxrankid')->from(array('fenxiao', 'a'))
            ->join(array('member', 'c'), 'inner')
            ->on('a.memberid', '=', 'c.mid')
            ->where('a.fxpcode', '=', $fxcode)
            ->and_where('a.status', '=', -1);

        if ( ! empty($keyword)) {
            $builder->and_where(DB::expr(" and sline_c.nickname like '%{$keyword}%' or sline_c.mobile like '%{$keyword}%' or sline_c.email like '%{$keyword}%'"));
        }
        $builder->order_by('a.fxjointime', 'desc');
        $total = $builder->execute()->count();
        $list = $builder->offset($offset)->limit($pagesize)->execute()->as_array();

        foreach ($list as &$row) {
            $total_amount = DB::select(DB::expr("sum(amount) as total"))->from('fenxiao_record')
                ->where('memberid', '=', $mid)
                ->and_where('type', '=', 0)
                ->and_where('fxmemberid', '=', $row['memberid'])
                ->group_by('fxmemberid')
                ->execute()->get('total');
            $row['total'] = ! is_null($total_amount) ? $total_amount : 0.00;
            $member_info = Model_Member::get_member_byid($row['memberid']);
            $row['nickname'] = $member_info['nickname'];
            $row['litpic'] = Model_Api_V2_Common::get_member_header_pic($member_info['litpic']);
            $row['account'] = empty($member_info['mobile']) ? $member_info['email'] : $member_info['mobile'];
        }
        return array('list' => $list, 'total' => $total);
    }

    /**
     * 获取我的下级分销商列表
     * @return mixed
     */
    public function get_sub_distributor($params)
    {
        $group = $params['group'];
        $mid = $params['mid'];
        $keyword = $params['keyword'];
        $page = (int)$params['page'];
        $page = $page < 1 ? 1 : $page;
        $pagesize = 10;
        $offset = ($page - 1) * $pagesize;

        $level_num = Model_Fenxiao_Config::get_val('cfg_fenxiao_level_num');
        $fenxiao_level_num = $level_num == 2 ? 2 : 3;
        $sub_mids = Model_Fenxiao::get_sub_mids($mid, $fenxiao_level_num);
        if ($group) {
            $sub_mids = Model_Fenxiao::get_sub_mids($mid, $group, true);
        }
        if (empty($sub_mids)) {
            return array();
        }
        $builder = DB::select('a.memberid', 'a.fxjointime', 'a.fxrankid')->from(array(
            'fenxiao',
            'a'
        ))->join(array('member', 'c'), 'inner')
            ->on('a.memberid', '=', 'c.mid')
            ->where('a.status', '=', 1)
            ->and_where('a.memberid', 'in', $sub_mids);
        if ($keyword) {
            $builder->and_where(DB::expr(" and (sline_c.nickname like '%{$keyword}%' or sline_c.mobile like '%{$keyword}%' or sline_c.email like '%{$keyword}%') "));
        }
        $builder->order_by('a.fxjointime', 'desc')->offset($offset)->limit($pagesize);

        $list = $builder->execute()->as_array();
        foreach ($list as &$row) {
            $total_amount = DB::select(DB::expr("sum(amount) as total"))->from('fenxiao_record')
                ->where('memberid', '=', $mid)
                ->and_where('type', '=', 0)
                ->and_where('fxmemberid', '=', $row['memberid'])
                ->group_by('fxmemberid')
                ->execute()->get('total');
            $member_info = Model_Member::get_member_byid($row['memberid']);
            $row['nickname'] = $member_info['nickname'];
            $row['litpic'] = Model_Api_V2_Common::get_member_header_pic($member_info['litpic']);
            $row['fxrank_name'] = Model_Fenxiao_Rank::get_name($row['fxrankid']);
            $row['sub_num'] = count(Model_Fenxiao::get_sub_mids($row['memberid'], 1));
            $row['fx_jointime'] = date('Y-m-d', $row['fxjointime']);
            $row['account'] = empty($member_info['mobile']) ? $member_info['email'] : $member_info['mobile'];
            $row['sub_level'] = Model_Fenxiao::get_rank($mid, $row['memberid']);
            $row['total'] = ! is_null($total_amount) ? $total_amount : 0;
            $row['member_id'] = $row['memberid'];
            unset($row['fxjointime'], $row['fxrankid'], $row['memberid']);
        }
        return $list;
    }

    /**
     * 获取可分销的产品列表
     * @param $params
     * @return array
     * User: netman
     * Date: 2023/9/21 14:19
     */
    public function get_products($params)
    {
        $type_id = $params['type_id'];
        $mid = $params['mid'];
        $keyword = $params['keyword'];
        $ordertype = $params['order_type'];
        $page = $params['page'] ?? 1;
        $pagesize = $params['pagesize'] ?? 20;
        $platform_no = $params['platform_no'];

        //分销分组ID
        $fx_group_id = DB::select('fxgroupid')->from('fenxiao')->where("memberid", '=',
            $mid)->execute()->get('fxgroupid');
        $list = $this->search_products(array(
            'type_id' => $type_id,
            'ordertype' => $ordertype,
            'groupid' => $fx_group_id,
            'page' => $page,
            'pagesize' => $pagesize,
            'platform_no' => $platform_no
        ), $keyword);
        $list_new = array();
        foreach ($list as $key => $v) {
            $commission_type = Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$type_id, $fx_group_id);
            $v['commission_type'] = $commission_type;
            $min_price = $this->get_price($type_id, $v['tid']);
            $v['price'] = $min_price;
            $v['id'] = $v['tid'];

            //产品最低利润，按平台收入百分比时用！
            list($minprofit,$suitid)=Model_Api_V2_Discount::get_profit_suitid($type_id,$v);
            $v['minprofit'] = $minprofit;
            $v['suitid'] = $suitid;

            $v['profit'] = $this->get_distributor_estimate_profit($type_id, $mid, $v['id'], $v['price'],$v)['profit'];
            $profit = round($v['profit'], 2);
            $v['typeid'] = $type_id;
            $module_info = ORM::factory('model', $type_id)->as_array();
            $v['label'] = $module_info['modulename'];//标签
            $v['producttitle'] = $v['title'];//标题
            $v['series'] = Product::product_number($v['tid'], $type_id);//编号
            $v['litpic'] = $this->img_url($v['litpic']);
            $icons = $this->icons($v['iconlist']);
            $attrlist = Model_Api_V2_Product::get_product_attr($v['attrid'], $module_info['maintable']);

            $list_new[] = array(
                'title' => $v['title'],
                'litpic' => $v['litpic'],
                'profit' => $profit,
                'bookcount' => Model_Member_Order::get_sell_num($v['tid'], $type_id) + (int)($v['bookcount']),
                'satisfyscore' => str_replace('%','',St_Functions::get_satisfy($type_id, $v['id'], $v['satisfyscore'])),
                'series' => $v['series'],
                'typeid' => $type_id,
                'id' => $v['tid'],
                'mid' => $mid,
                'price' => $v['price'],
                'iconlist' => $icons,
                'attrlist' => $attrlist,
            );
        }
        //按照佣金升序排列
        if ($ordertype == 3) {
            $list_new = $this->assort_array($list_new, 'SORT_ASC', 'profit');
        }
        //按照佣金降序排列
        if ($ordertype == 4) {
            $list_new = $this->assort_array($list_new, 'SORT_DESC', 'profit');
        }
        return $list_new;
    }

    //获取产品，必须要有tid 和 typeid
    private function search_products($params, $keyword)
    {
        $table = $this->get_main_table($params['type_id']);
        if (empty($table)) {
            return array(
                'total' => 0,
                'list' => null
            );
        }

        $field = [
            'sline_a.title',
            'sline_a.litpic',
            'sline_a.satisfyscore',
            'sline_a.id as tid',
            'sline_a.modtime',
            'sline_a.price',
            'sline_a.attrid',
            'sline_a.iconlist',
            'sline_a.addtime',
            'sline_b.*',
        ];
        if ($params['type_id'] == 13) {
            $field[] = 'sline_a.virtualnum as bookcount';
        } else {
            $field[] = 'sline_a.bookcount';
        }
        if($params['type_id']==198){
            unset($field[2]);
            unset($field[7]);
            unset($field[10]);
        }
        if(in_array($params['type_id'],[8])){
            unset($field[6]);
        }

        $builder = DB::select(DB::expr(implode(',', $field)))
            ->from(array($table, 'a'))->join(array('fenxiao_ratio', 'b'), 'left')
            ->on('a.id', '=', 'b.productid')
            ->on('b.typeid', '=', 1)
            ->on('b.groupid', '=', (int)$params['groupid'])
            ->and_where('a.fenxiao_status', '=', 1);
        if(in_array($params['type_id'],[5,2,13])){//暂时平台端只有 酒店 团购 景点
            $builder ->and_where(DB::expr(" and FIND_IN_SET({$params['platform_no']},sline_a.platform) "));
        }else{
            $builder->and_where('a.ishidden', '=', 0);
        }
        if (is_numeric($keyword)) {
            $result = St_Product::product_series($keyword, '', true);
            $builder->and_where('a.id', '=', (int)$result['id']);
        } else {
            if ( ! empty($keyword)) {
                //关键字查询
                $builder->and_where('a.title', 'like', '%'.$keyword.'%');
            }
        }
        if ($table == 'model_archive') {
            $builder->and_where('a.typeid', '=', (int)$params['type_id']);
        }
        switch ($params['ordertype']) {
            case 1://综合排序
                $builder->order_by(DB::expr("ifnull(sline_b.displayorder,999999)"), 'asc');
                $builder->order_by('b.cash1', 'desc');
                break;
            case 2://热度排序
                $builder->order_by('a.bookcount', 'desc');
                $builder->order_by('b.cash1', 'desc');
                break;
            case 5://最新商品
                $builder->order_by('a.addtime', 'desc');
                $builder->order_by('b.cash1', 'desc');
                break;
        }
        $offset = ($params['page'] -1) * $params['pagesize'];
        return $builder->offset($offset)->limit($params['pagesize'])->execute()->as_array();
    }

    //获取某个产品的最低价
    public function get_price($typeid, $productid)
    {
        $model_info = DB::select()->from('model')->where('id', '=', $typeid)->execute()->current();
        $maintable = $model_info['maintable'];
        $letter_arr = explode('_', $maintable);
        foreach ($letter_arr as &$letter) {
            $letter = ucfirst($letter);
        }
        $class_name = 'Model_'.implode('_', $letter_arr);
        $price = 0;
        if (class_exists($class_name) && method_exists($class_name, 'get_minprice')) {
            $price = call_user_func(array($class_name, 'get_minprice'), $productid);
            $price = is_array($price) ? $price['price'] : $price;
        }

        return $price;
    }

    //获取收益
    private function get_prospect_fenxiao_price($typeid, $product, $fxgroupid)
    {
        $commission_type = Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$typeid, $fxgroupid);
        $min_price = $this->get_price($typeid, $product['id']);

        $product['price'] = empty($product['price']) ? 0 : $product['price'];
        $min_price = is_array($min_price) ? $min_price['price'] : $min_price;
        $min_price = empty($min_price) ? 0 : $min_price;
        $product['price'] = ! empty($min_price) ? $min_price : $product['price'];

        if ($commission_type == 1) {
            $commission_rate = Model_Fenxiao::get_commission_rate($typeid, $product['id'], $fxgroupid);
            $profit = number_format($product['price'] * $commission_rate[0], 2);
        } else {
            if ($commission_type == 2) {
                $commission_rate = Model_Fenxiao::get_commission_rate_platform($typeid, $product['id'], $fxgroupid);


                $temp_order = array(
                    'typeid' => $typeid,
                    'productautoid' => $product['id'],
                    'totalprice' => $product['price'],
                    'dingnum' => 1
                );

                if ($typeid == 5) {
                    $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
                } else {
                    $platform_price = empty($product['supplierlist']) ? $product['price'] : Model_Member_Order_Compute::caculate_platform_commission($temp_order);
                }


                $profit = number_format($platform_price * $commission_rate[0], 2);
            } else {
                $commission_cash = Model_Fenxiao::get_commission_cash_line($typeid, $product['id'], $fxgroupid);
                if ($typeid == 1) {
                    $time = strtotime(date('Y-m-d', time()));
                    //取该产品的今天有报价的那1个套餐
                    $sql_suit = "select propgroup from sline_line_suit_price where day>=".$time.' and lineid = '.$product['id'].' order by suitid asc';
                    $suit_data = DB::query(1, $sql_suit)->execute()->current();
                    //2:成人 1:小孩 3:老人,4:人群四，5：人群五，6：人群6
                    //假如报了儿童，就在佣金设置里面找儿童的收益
                    $people_relationship = [
                        1 => 'child',
                        2 => 'adult',
                        3 => 'old',
                        4 => 'people4',
                        5 => 'people5',
                        6 => 'people6',
                    ];
                    $_profit = [];
                    //如果有报价
                    if ($suit_data['propgroup']) {
                        $propgroup = explode(',', $suit_data['propgroup']);//该套餐的报价人群
                        foreach ($propgroup as $propgroup_v) {
                            if (isset($people_relationship[$propgroup_v])) {
                                $_people = $people_relationship[$propgroup_v];//报价人群
                                $_profit[] = $commission_cash[0][$_people];
                            }
                        }
                    }
                    $profit = number_format(max($_profit), 2);//金额最大的
                } else {
                    $profit = number_format($commission_cash[0]['adult'], 2);
                }
            }
        }
        return $profit;
    }

    private function get_distributor_estimate_profit($typeid, $user_id, $product_id, $product_price,$product)
    {
        $fxgroupid = DB::select('fxgroupid')->from('fenxiao')->where("memberid", '=', $user_id)->execute()->current();
        $commission_type = Model_Fenxiao_Config::get_val(
            'cfg_fenxiao_commission_type_'.$typeid,
            $fxgroupid['fxgroupid']
        );
        //按订单金额百分比
        if ($commission_type == 1) {
            $commission_rate = Model_Fenxiao::get_commission_rate($typeid, $product_id, $fxgroupid['fxgroupid']);
            $v['commission'] = bcmul($commission_rate[0], '100');
            $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
            $v['commission'] .= '%';
            $v['profit'] = bcmul($product_price, $commission_rate[0],2);
        } else {
            //按平台收入百分比
            if ($commission_type == 2) {
                $commission_rate = Model_Fenxiao::get_commission_rate_platform(
                    $typeid,
                    $product_id,
                    $fxgroupid['fxgroupid']
                );
                $v['commission'] = $commission_rate[0] * 100;
                $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
                $v['commission'] .= '%';
                $temp_order = array(
                    'typeid' => $typeid,
                    'productautoid' => $product_id,
                    'suitid' => $product['suitid'],
                    'totalprice' => $product_price,
                    'channel_id' => 1,
                    'dingnum' => 1
                );
                $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
                if($platform_price['settlement_type']==2){//销售价-获取销售最低价
                    $platform_price = $product_price;
                }else{//结算价模式-获取最低利润报价
                    $platform_price = $product['minprofit'];
                }

            $v['profit'] = $platform_price * $commission_rate[0];
            } else {
                //现金
                $commission_cash = Model_Fenxiao::get_commission_cash_line(
                    $typeid,
                    $product_id,
                    $fxgroupid['fxgroupid']
                );
                $v['commission'] = $commission_cash[0]['adult'];
                $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
                $v['profit'] = $v['commission'];
            }
        }
        return $v;
    }

    //排序
    private function assort_array($array, $flag, $keyword)
    {
        $sort = array(
            'direction' => $flag, //排序顺序标志 1 ，SORT_DESC 降序；2 ，SORT_ASC 升序
            'field' => $keyword,       //排序字段
        );
        $arrSort = array();
        foreach ($array as $uniqid => $row) {
            foreach ($row as $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        if ($sort['direction']) {
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $array);
        }
        return $array;
    }

    protected function get_invite_code($xurl, $comefrom, $mid)
    {
        //获得分销信息
        $fenxiao = DB::select()->from('fenxiao')->where('memberid', '=', $mid)->execute()->current();
        $fenxiao['fxrank_name'] = Model_Fenxiao_Rank::get_name($fenxiao['fxrankid']);

        //分销二维码
        if ($comefrom == 'wechat') {//微信小程序
            // 获取分销配置信息
            $appid = Model_Api_V2_System::get_fenxiao_para('cfg_wxxcx_appid');
            $secret = Model_Api_V2_System::get_fenxiao_para('cfg_wxxcx_appsecret');
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
            $access_token = Model_Api_V2_Pub::makeRequest($url);
            $access_token = json_decode($access_token['result'], true);
            $codeRes = Model_Api_V2_Pub::getWxcode($xurl, $mid, $fenxiao['fxcode'], $access_token, null);

            if ( ! $codeRes['status']) { // 获取二维码失败
                return $codeRes;
            }
            // 保存路径及文件名
            $path = '/uploads/uniapp/invite/wechat/'.date('Y').'/';
            $filename = md5($fenxiao['fxcode'].$xurl.$mid);
            // 创建图片并返回路径
            $imgPath = Model_Api_V2_Pub::base64_image_content($codeRes['data'], $path, $filename);
            return array('status' => true, 'msg' => '', 'path' => $imgPath);
        } else {
            if ($comefrom == 'h5') {//h5

                $share_url = $xurl.'?fxpcode='.$fenxiao['fxcode'];
                $share_url = Model_Api_V2_System::reorganized_resource_url($share_url);
                $path = '/uploads/uniapp/invite/h5/'.date('Y').'/';
                $filename = md5($fenxiao['fxcode'].$share_url.$mid);
                //获得logo
                $logo = Model_Api_V2_System::reorganized_resource_url(Model_Sysconfig::get_configs(0,
                    'cfg_fx_code_logo', true));

                $imgPath = $this->get_code_url($share_url, $path, $filename, $logo);
                return array('status' => true, 'msg' => '', 'path' => $imgPath);
            } else {
                return array('status' => false, 'msg' => '不支持该类型海报分销');
            }
        }
    }

    /**
     * 获取产品分销二维码
     * @param $xcxurl
     * @param $pid
     * @param $userid
     * @param $comefrom
     * @return array
     */
    private function get_product_code($xcxurl, $pid, $userid, $comefrom, $_t)
    {
        //获得分销信息
        $fenxiao = DB::select()->from('fenxiao')->where('memberid', '=', $userid)->execute()->current();
        $fenxiao['fxrank_name'] = Model_Fenxiao_Rank::get_name($fenxiao['fxrankid']);

        if ($comefrom == 'wechat') {
            // 获取分销配置信息
            $appid = Model_Api_V2_System::get_fenxiao_para('cfg_wxxcx_appid');
            $secret = Model_Api_V2_System::get_fenxiao_para('cfg_wxxcx_appsecret');
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
            $access_token = Model_Api_V2_Pub::makeRequest($url);
            $access_token = json_decode($access_token['result'], true);
            // 获取当前用户的分销码
            $userFxCode = DB::select('fxcode')->from('fenxiao')->where('memberid', '=', $userid)->and_where('status',
                '=', 1)->execute()->current();
            $codeRes = Model_Api_V2_Pub::getWxcode($xcxurl, $pid, $userFxCode['fxcode'], $access_token, $_t);
            if ( ! $codeRes['status']) { // 获取二维码失败
                return $codeRes;
            }
            // 保存路径及文件名
            $path = '/uploads/uniapp/productCode/wechat/'.date('Y').'/';
            $filename = md5($userFxCode['fxcode'].$xcxurl.$pid);
            // 创建图片并返回路径
            $imgPath = Model_Api_V2_Pub::base64_image_content($codeRes['data'], $path, $filename);
            return array('status' => true, 'msg' => '', 'path' => $imgPath);
        } else {
            if ($comefrom == 'h5') {
                $path = '/uploads/uniapp/productCode/h5/'.date('Y').'/';
                $filename = md5($fenxiao['fxcode'].$xcxurl.$pid);
                $xcxurl = $GLOBALS['cfg_basehost'].'/'.$xcxurl.'&fxpcode='.$fenxiao['fxcode'];
                $imgPath = $this->get_code_url($xcxurl, $path, $filename);
                return array('status' => true, 'msg' => '', 'path' => $imgPath);
            } else {
                return array('status' => false, 'msg' => '不支持该类型海报分销');
            }
        }
    }

    /**
     * @param $share_url 二维码内容
     * @param $path 二维码存储路径
     * @param $filename 文件名
     * @param  bool  $logo  是否需要logo
     * @return bool|string
     */
    private function get_code_url($share_url, $path, $filename, $logo = false)
    {
        require_once BASEPATH."/plugins/api/vendor/qrcode/phpqrcode.php";
        $errorCorrectionLevel = "Q";
        $matrixPointSize = 4;
        QRcode::png($share_url, false, $errorCorrectionLevel, $matrixPointSize);
        $imageString = base64_encode(ob_get_contents());
        ob_end_clean();
        $code = "data:image/png;base64,".$imageString;

        // 创建图片并返回路径
        $imgPath = Model_Api_V2_Pub::base64_image_content($code, $path, $filename);

        if ($logo !== false) {
            $QR = imagecreatefromstring(file_get_contents($imgPath));
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR);//二维码图片宽度
            $QR_height = imagesy($QR);//二维码图片高度
            $logo_width = imagesx($logo);//logo图片宽度
            $logo_height = imagesy($logo);//logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                $logo_qr_height, $logo_width, $logo_height);
            $imgagename = '.'.$path.$filename.'.png';
            //输出图片
            imagepng($QR, $imgagename);
            imagedestroy($QR);
            imagedestroy($logo);
        }
        return $imgPath;
    }

    /**
     * @function 获取价格团期
     * @param $productid
     * @param $typeid
     * @return string
     */
    private function get_product_price_date($productid, $typeid)
    {
        $limit = 4;
        $now_time = time();
        if ($typeid == 1) { // 线路
            $price_table = 'sline_line_suit_price';
            $id_name = 'lineid';
        } else {
            if ($typeid == 2) { // 酒店
                $price_table = 'sline_hotel_room_price';
                $id_name = 'hotelid';
            } else {
                if ($typeid == 3) { // 租车
                    $price_table = 'sline_car_suit_price';
                    $id_name = 'carid';
                } else {
                    if ($typeid == 5) { // 景点
                        $price_table = 'sline_spot_ticket_price';
                        $id_name = 'spotid';
                    } else {
                        if ($typeid == 13) { // 团购
                            $price_table = 'sline_tuan_price';
                            $id_name = 'tuan_id';
                        } else {
                            if ($typeid == 104) { // 邮轮
                                $price_table = 'sline_ship_line_suit_price';
                                $id_name = 'lineid';
                            } else {
                                if ($typeid == 114) { // 户外
                                    $price_table = 'sline_outdoor_suit_price';
                                    $id_name = 'outdoorid';
                                }
                            }
                        }
                    }
                }
            }
        }

        if ($price_table && $id_name) {
            $sql = "SELECT `day` FROM {$price_table} WHERE `day`>{$now_time} AND `{$id_name}`={$productid} GROUP BY `day` ORDER BY `day` ASC LIMIT {$limit} ";
            $list = DB::query(1, $sql)->execute()->as_array();
            if ( ! empty($list)) {
                $str = '使用时间：';
                $date_arr = array();
                foreach ($list as $v) {
                    array_push($date_arr, date('Y-m-d', $v['day']));
                }

                $dateStr = implode('、', $date_arr);
                $str .= $dateStr.'......';
                return $str;
            }
        }

        return '';
    }

    //邀请成为分销商二维码

    private function get_open_model()
    {
        return Model_Fenxiao::get_fenxiao_product();
    }

    private function check_distribution($userid){
        $info = DB::select('isfrozen', 'fxcode')->from('fenxiao')->where('memberid', '=', $userid)->and_where('status','=','1')->and_where('isfrozen','=','0')->execute()->current();
        return $info;
    }





}